﻿using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows.Forms;

namespace APBR_Patch_Mirror
{
    public partial class ProgUpdater : Form
    {
        public static int version = 10088;
        public static int verify = 0;
        public static string buildDate = "10/16/2011";
        public ProgUpdater()
        {
            this.Name = Console.Title;
            InitializeComponent();
            getversion();
            label2.Text = verify.ToString();
            label3.Text = buildDate;
        }

        public void getversion()
        {
            WebClient webClient = new WebClient();
            verify = Int16.Parse(webClient.DownloadString("http://apbcorner.com/APB_Reloaded/APB_Repair/Version.php"));
        }

        private void done_Click(object sender, EventArgs e)
        {
            if (version != verify)
            {
                new Thread(StartUpdate).Start();
            }
            else
            {
                this.Close();
            }
        }

        private void StartUpdate()
        {
            try
            {
                WebClient webClient = new WebClient();
                label2.Text = verify.ToString(); Uri uri = new Uri("http://apbcorner.com/APB_Reloaded/APB_Repair/" + verify + ".exe");
                webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
                webClient.DownloadFileAsync(uri, "latest.exe");
                do { Thread.Sleep(1); } while (webClient.IsBusy);
                webClient.Dispose();
                File.Replace("latest.exe", Process.GetCurrentProcess().MainModule.FileName, "APB Repair.bak", true);
                Process.Start(Process.GetCurrentProcess().MainModule.FileName);
                MessageBox.Show("Update Complete");
                Environment.Exit(-1);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                File.AppendAllText(Sanity.log, ex.ToString() + Environment.NewLine + "--------------------------------------------------------" + Environment.NewLine);
                Environment.Exit(-1);
            }
        }

        private void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
        {
            progressBar1.Maximum = Convert.ToInt32(e.TotalBytesToReceive);
            progressBar1.Value = Convert.ToInt32(e.BytesReceived); 
        }
    }
}
